<template>
  <div class="inventory-warning-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分派任务</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleCreateRule"
              >新建预警规则</el-button
            >
            <el-button type="warning" @click="handleRefreshWarning"
              >刷新预警</el-button
            >
          </div>
        </div>
      </template>

      <!-- 预警规则列表 -->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="预警规则" name="rules">
          <el-form :inline="true" :model="ruleQueryForm" class="search-form">
            <el-form-item label="物料编码">
              <el-input
                v-model="ruleQueryForm.materialCode"
                placeholder="请输入物料编码"
              />
            </el-form-item>
            <el-form-item label="物料名称">
              <el-input
                v-model="ruleQueryForm.materialName"
                placeholder="请输入物料名称"
              />
            </el-form-item>
            <el-form-item label="预警类型">
              <el-select
                v-model="ruleQueryForm.type"
                placeholder="请选择预警类型"
              >
                <el-option label="库存上限" value="upper" />
                <el-option label="库存下限" value="lower" />
                <el-option label="积压预警" value="overstock" />
                <el-option label="呆滞预警" value="stagnant" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="ruleQueryForm.status"
                placeholder="请选择状态"
              >
                <el-option label="启用" value="enabled" />
                <el-option label="停用" value="disabled" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRuleSearch"
                >查询</el-button
              >
              <el-button @click="handleRuleReset">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="ruleTableData" border style="width: 100%">
            <el-table-column prop="materialCode" label="物料编码" width="150" />
            <el-table-column
              prop="materialName"
              label="物料名称"
              min-width="150"
            />
            <el-table-column
              prop="specification"
              label="规格型号"
              width="120"
            />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="type" label="预警类型" width="100">
              <template #default="scope">
                {{ getWarningTypeText(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="threshold" label="预警阈值" width="120">
              <template #default="scope">
                <template v-if="scope.row.type === 'upper'">
                  大于 {{ scope.row.threshold }}
                </template>
                <template v-else-if="scope.row.type === 'lower'">
                  小于 {{ scope.row.threshold }}
                </template>
                <template v-else-if="scope.row.type === 'overstock'">
                  {{ scope.row.threshold }} 天未出库
                </template>
                <template v-else-if="scope.row.type === 'stagnant'">
                  {{ scope.row.threshold }} 天未移动
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="warehouse" label="仓库" width="120" />
            <el-table-column prop="notifyType" label="通知方式" width="120">
              <template #default="scope">
                <el-tag
                  v-if="scope.row.notifyType.includes('email')"
                  size="small"
                  >邮件</el-tag
                >
                <el-tag
                  v-if="scope.row.notifyType.includes('sms')"
                  type="success"
                  size="small"
                  class="ml-5"
                  >短信</el-tag
                >
                <el-tag
                  v-if="scope.row.notifyType.includes('system')"
                  type="warning"
                  size="small"
                  class="ml-5"
                  >系统</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'enabled' ? 'success' : 'info'"
                >
                  {{ scope.row.status === "enabled" ? "启用" : "停用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleEditRule(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  link
                  :type="scope.row.status === 'enabled' ? 'danger' : 'success'"
                  @click="handleToggleRule(scope.row)"
                  >{{
                    scope.row.status === "enabled" ? "停用" : "启用"
                  }}</el-button
                >
                <el-button
                  link
                  type="danger"
                  @click="handleDeleteRule(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="ruleCurrentPage"
              v-model:page-size="rulePageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="ruleTotal"
              @size-change="handleRuleSizeChange"
              @current-change="handleRuleCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 预警记录列表 -->
        <el-tab-pane label="预警记录" name="records">
          <el-form :inline="true" :model="recordQueryForm" class="search-form">
            <el-form-item label="物料编码">
              <el-input
                v-model="recordQueryForm.materialCode"
                placeholder="请输入物料编码"
              />
            </el-form-item>
            <el-form-item label="物料名称">
              <el-input
                v-model="recordQueryForm.materialName"
                placeholder="请输入物料名称"
              />
            </el-form-item>
            <el-form-item label="预警类型">
              <el-select
                v-model="recordQueryForm.type"
                placeholder="请选择预警类型"
              >
                <el-option label="库存上限" value="upper" />
                <el-option label="库存下限" value="lower" />
                <el-option label="积压预警" value="overstock" />
                <el-option label="呆滞预警" value="stagnant" />
              </el-select>
            </el-form-item>
            <el-form-item label="预警日期">
              <el-date-picker
                v-model="recordQueryForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="处理状态">
              <el-select
                v-model="recordQueryForm.status"
                placeholder="请选择状态"
              >
                <el-option label="未处理" value="pending" />
                <el-option label="已处理" value="processed" />
                <el-option label="已忽略" value="ignored" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRecordSearch"
                >查询</el-button
              >
              <el-button @click="handleRecordReset">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="recordTableData" border style="width: 100%">
            <el-table-column prop="materialCode" label="物料编码" width="150" />
            <el-table-column
              prop="materialName"
              label="物料名称"
              min-width="150"
            />
            <el-table-column
              prop="specification"
              label="规格型号"
              width="120"
            />
            <el-table-column prop="type" label="预警类型" width="100">
              <template #default="scope">
                {{ getWarningTypeText(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="warningValue" label="预警值" width="100" />
            <el-table-column prop="currentValue" label="当前值" width="100" />
            <el-table-column prop="warningDate" label="预警日期" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getWarningStatusType(scope.row.status)">
                  {{ getWarningStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="processor" label="处理人" width="120" />
            <el-table-column prop="processDate" label="处理日期" width="180" />
            <el-table-column
              prop="processMethod"
              label="处理方式"
              width="150"
            />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleProcess(scope.row)"
                  v-if="scope.row.status === 'pending'"
                  >处理</el-button
                >
                <el-button
                  link
                  type="warning"
                  @click="handleIgnore(scope.row)"
                  v-if="scope.row.status === 'pending'"
                  >忽略</el-button
                >
                <el-button
                  link
                  type="primary"
                  @click="handleViewRecord(scope.row)"
                  >查看</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="recordCurrentPage"
              v-model:page-size="recordPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="recordTotal"
              @size-change="handleRecordSizeChange"
              @current-change="handleRecordCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新建/编辑预警规则对话框 -->
    <el-dialog
      v-model="ruleDialogVisible"
      :title="ruleDialogType === 'create' ? '新建预警规则' : '编辑预警规则'"
      width="600px"
    >
      <el-form
        :model="ruleForm"
        label-width="100px"
        :rules="ruleFormRules"
        ref="ruleFormRef"
      >
        <el-form-item label="物料" prop="materialCode">
          <el-select
            v-model="ruleForm.materialCode"
            filterable
            remote
            placeholder="请选择物料"
            :remote-method="handleMaterialSearch"
            :loading="materialLoading"
            @change="handleMaterialSelect"
            style="width: 100%"
          >
            <el-option
              v-for="item in materialOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预警类型" prop="type">
          <el-select
            v-model="ruleForm.type"
            placeholder="请选择预警类型"
            style="width: 100%"
          >
            <el-option label="库存上限" value="upper" />
            <el-option label="库存下限" value="lower" />
            <el-option label="积压预警" value="overstock" />
            <el-option label="呆滞预警" value="stagnant" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警阈值" prop="threshold">
          <el-input-number
            v-model="ruleForm.threshold"
            :min="0"
            :precision="
              ruleForm.type === 'upper' || ruleForm.type === 'lower' ? 2 : 0
            "
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouse">
          <el-select
            v-model="ruleForm.warehouse"
            placeholder="请选择仓库"
            style="width: 100%"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通知方式" prop="notifyType">
          <el-checkbox-group v-model="ruleForm.notifyType">
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
            <el-checkbox label="system">系统</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="通知人" prop="notifyUsers">
          <el-select
            v-model="ruleForm.notifyUsers"
            multiple
            filterable
            placeholder="请选择通知人"
            style="width: 100%"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ruleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRuleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预警处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="预警处理" width="500px">
      <el-form
        :model="processForm"
        label-width="100px"
        :rules="processFormRules"
        ref="processFormRef"
      >
        <el-form-item label="处理方式" prop="method">
          <el-select
            v-model="processForm.method"
            placeholder="请选择处理方式"
            style="width: 100%"
          >
            <el-option label="补货" value="replenish" />
            <el-option label="调拨" value="transfer" />
            <el-option label="清理" value="clear" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理说明" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleProcessSubmit"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 标签页
const activeTab = ref("rules");

// 预警规则相关
const ruleQueryForm = reactive({
  materialCode: "",
  materialName: "",
  type: "",
  status: "",
});

const ruleTableData = ref([]);
const ruleCurrentPage = ref(1);
const rulePageSize = ref(10);
const ruleTotal = ref(0);

// 预警记录相关
const recordQueryForm = reactive({
  materialCode: "",
  materialName: "",
  type: "",
  dateRange: [],
  status: "",
});

const recordTableData = ref([]);
const recordCurrentPage = ref(1);
const recordPageSize = ref(10);
const recordTotal = ref(0);

// 状态转换方法
const getWarningTypeText = (type) => {
  const map = {
    upper: "库存上限",
    lower: "库存下限",
    overstock: "积压预警",
    stagnant: "呆滞预警",
  };
  return map[type] || type;
};

const getWarningStatusType = (status) => {
  const map = {
    pending: "warning",
    processed: "success",
    ignored: "info",
  };
  return map[status] || "info";
};

const getWarningStatusText = (status) => {
  const map = {
    pending: "未处理",
    processed: "已处理",
    ignored: "已忽略",
  };
  return map[status] || status;
};

// 查询方法
const handleRuleSearch = () => {
  // 实现预警规则查询逻辑
};

const handleRuleReset = () => {
  ruleQueryForm.materialCode = "";
  ruleQueryForm.materialName = "";
  ruleQueryForm.type = "";
  ruleQueryForm.status = "";
  handleRuleSearch();
};

const handleRecordSearch = () => {
  // 实现预警记录查询逻辑
};

const handleRecordReset = () => {
  recordQueryForm.materialCode = "";
  recordQueryForm.materialName = "";
  recordQueryForm.type = "";
  recordQueryForm.dateRange = [];
  recordQueryForm.status = "";
  handleRecordSearch();
};

// 预警规则操作方法
const handleCreateRule = () => {
  ruleDialogType.value = "create";
  ruleForm.materialCode = "";
  ruleForm.type = "";
  ruleForm.threshold = 0;
  ruleForm.warehouse = "";
  ruleForm.notifyType = [];
  ruleForm.notifyUsers = [];
  ruleForm.remark = "";
  ruleDialogVisible.value = true;
};

const handleEditRule = (row) => {
  ruleDialogType.value = "edit";
  Object.assign(ruleForm, row);
  ruleDialogVisible.value = true;
};

const handleToggleRule = (row) => {
  const action = row.status === "enabled" ? "停用" : "启用";
  ElMessageBox.confirm(`确认${action}该预警规则？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现启用/停用逻辑
    ElMessage.success(`${action}成功`);
    handleRuleSearch();
  });
};

const handleDeleteRule = (row) => {
  ElMessageBox.confirm("确认删除该预警规则？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现删除逻辑
    ElMessage.success("删除成功");
    handleRuleSearch();
  });
};

// 预警记录操作方法
const handleProcess = (row) => {
  currentRecord.value = row;
  processForm.method = "";
  processForm.remark = "";
  processDialogVisible.value = true;
};

const handleIgnore = (row) => {
  ElMessageBox.confirm("确认忽略该预警记录？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现忽略逻辑
    ElMessage.success("已忽略");
    handleRecordSearch();
  });
};

// 分页方法
const handleRuleSizeChange = (val) => {
  rulePageSize.value = val;
  handleRuleSearch();
};

const handleRuleCurrentChange = (val) => {
  ruleCurrentPage.value = val;
  handleRuleSearch();
};

const handleRecordSizeChange = (val) => {
  recordPageSize.value = val;
  handleRecordSearch();
};

const handleRecordCurrentChange = (val) => {
  recordCurrentPage.value = val;
  handleRecordSearch();
};

// 刷新预警
const handleRefreshWarning = () => {
  // 实现预警刷新逻辑
  ElMessage.success("预警刷新成功");
  handleRecordSearch();
};
</script>

<style scoped>
.inventory-warning-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.ml-5 {
  margin-left: 5px;
}

.dialog-footer {
  text-align: right;
}
</style>
